package com.lazyframework.security.web.configuration.configurer;

import com.lazyframework.security.web.JwtClients;
import com.lazyframework.security.web.authentication.AuthenticationManager;
import com.lazyframework.security.web.authentication.AuthorizationType;
import com.lazyframework.security.web.authentication.UserDetailsService;
import com.lazyframework.security.web.authentication.filter.JwtAuthenticationFilter;
import com.lazyframework.security.web.authentication.provider.JwtAuthenticationProvider;
import com.lazyframework.security.web.configuration.HttpSecurity;
import com.lazyframework.security.web.configuration.SecurityConfigurerAdapter;

import javax.servlet.Filter;

public class JwtAuthenticationConfigurer extends SecurityConfigurerAdapter<Filter, HttpSecurity> {

    private JwtClients jwtClients;

    private UserDetailsService userDetailsService;

    public JwtAuthenticationConfigurer() {
    }

    public JwtAuthenticationConfigurer userDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
        return this;
    }

    public JwtAuthenticationConfigurer jwtClients(JwtClients jwtClients) {
        this.jwtClients = jwtClients;
        return this;
    }

    @Override
    public void configure(HttpSecurity builder) {
        AuthenticationManager authenticationManager = builder.authenticationManager();

        // JWT 认证提供者
        JwtAuthenticationProvider provider = new JwtAuthenticationProvider();

        provider.setJwtClients(jwtClients);
        provider.setUserDetailsService(userDetailsService);

        // 向认证管理器注册认证提供者
        authenticationManager.registerProvider(provider);

        JwtAuthenticationFilter filter = new JwtAuthenticationFilter();

        filter.setAuthorizationType(AuthorizationType.BEARER);
        filter.setAuthenticationManager(authenticationManager);

        builder.addFilter(filter);
    }

}
